package com.xckj.ibox.utils;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.webkit.JavascriptInterface;

import com.xckj.ibox.App;
import com.xckj.ibox.event.HideTabBarEvent;
import com.xckj.ibox.event.ShowTabBarEvent;
import com.xckj.ibox.global.Constant;
import com.xckj.ibox.ui.activity.HomeActivity;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * @Author: ChenYao
 * @Describe: 定义与H5交互的方法
 * @Date: 2023/6/19 19:00
 */
public class JsAction {
    private final Activity mActivity;
    private final Handler mHandler = new Handler(Looper.getMainLooper());

    public JsAction(Activity mActivity) {
        this.mActivity = mActivity;
    }


    @JavascriptInterface
    public void onBackPress() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mActivity.onBackPressed();
            }
        });
    }

    @JavascriptInterface
    public String loadUserInfo() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("capttoken", SpUtil.getString(App.getInstance(), Constant.APP_TOKEN));
            jsonObject.put("token", SpUtil.getString(App.getInstance(), Constant.TOKEN));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject.toString();
    }

    @JavascriptInterface
    public String currentVersion() {
        return AndroidUtil.getVersionName();
    }

    @JavascriptInterface
    public void loginOut() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                SpUtil.remove(App.getInstance(), Constant.APP_TOKEN);
                SpUtil.remove(App.getInstance(), Constant.TOKEN);
                SpUtil.remove(App.getInstance(), Constant.IS_AUTO_LOGIN);
                App.getInstance().startActivity(new Intent(App.getInstance(), HomeActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
            }
        });
    }

    @JavascriptInterface
    public void showTabBar() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                EventBus.getDefault().post(new ShowTabBarEvent());
            }
        });
    }

    @JavascriptInterface
    public void hideTabBar() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                EventBus.getDefault().post(new HideTabBarEvent());
            }
        });
    }

    @JavascriptInterface
    public void shareWechat() {

    }

    @JavascriptInterface
    public void shareWechatQuan() {

    }

    @JavascriptInterface
    public void shareQQFriends() {

    }
}
